package library;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.j256.ormlite.dao.Dao;

public class BookingController {
	private static Dao<BookingRecord, String> bookingDao;
	private BookController bookController;
	private Reader user;
	private List<BookingRecord> bookedRecord ;
	
	public BookingController(Reader user) throws SQLException{
		bookingDao = DaoUtil.getDao(BookingRecord.class);
		bookController = new BookController();
		this.user = user;
		bookedRecord = new ArrayList<BookingRecord>();
	}

	public List<BookingRecord> getBookingRecord() throws SQLException{
		bookedRecord = bookingDao.queryForEq("user_id", user.getId());
		return this.bookedRecord;
	}

    public Book bookRecord(int book_id) throws Exception {
        Book book = bookController.getBookById(book_id);
        Date date = new Date();
        BookingRecord bk_rec= new BookingRecord(book, date, user);
        if(book.getStatus() != BookStatus.avaliable)
            throw new Exception ("Book " + book.getName() + " (id:" + book.getId()  + ") already reserved and cannot booked.");
        if(bookingDao.create(bk_rec) == 1){
            bookController.updateStatus(book, BookStatus.reserved);
        } else {
            throw new Exception ("Can not book item.");
        }
        return book;
    }

	public boolean returnBooked(Book book) throws Exception{
		int result = -1;

		List<BookingRecord> recordResult = bookingDao.queryForEq("res_id", book.getId());

        if (recordResult.size() > 0) {
            result = bookingDao.delete(recordResult.get(0));
        } else if (book.getStatus() != BookStatus.reserved) {
            throw new Exception("Book " + book.getName() + " (id:" + book.getId() + ") is not reserved");
        } else {
            throw new Exception("No related booking record, book: " + book.getName() + "  statue will change to available.");
        }

        bookController.updateStatus(book, BookStatus.avaliable);
		return result == 1;
	}
	
	public Book returnBooked(int book_id) throws Exception{
		Book book_rtn = bookController.getBookById(book_id);
		if(returnBooked(book_rtn))
			return book_rtn;
		else 
			return null;
	}
	
}
